<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor style="overflow-y: hidden" :style="{ height: height }" v-model="valueHtml" :defaultConfig="editorConfig"
      :mode="mode" @onCreated="handleCreated" />
  </div>
</template>

<script lang="ts">
// TODO 须测试
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { serverDefaultCfg } from '@/common/http/config';

const defaultEditorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 小于该值就插入 base64 格式（而不上传），默认为 0
      base64LimitSize: 0, // 设置为0，确保所有图片都以URL形式上传
      server: serverDefaultCfg.baseURL + 'file/ali/upload',
      fieldName: 'file',
      maxFileSize: 10 * 1024 * 1024, // 10MB
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      // 自定义上传
      customUpload(file: File, insertFn: any) {
        const formData = new FormData();
        formData.append('file', file);

        fetch(serverDefaultCfg.ossURL, {
          method: 'POST',
          body: formData,
        })
          .then(res => res.json())
          .then(res => {
            if (res.data?.downloadUri) {
              insertFn(res.data.downloadUri, res.data.filename, res.data.downloadUri);
            }
          })
          .catch(err => {
            console.error('Upload failed:', err);
          });
      },
      // 上传之前触发
      onBeforeUpload(file: File) {
        return file;
      },
      // 上传成功后触发
      onSuccess(file: File, res: any) {
        console.log('upload success', file, res);
        // 判断接口返回结果
        if (!res.data?.downloadUri) {
          console.error('Upload response downloadUri is empty:', res);
          return null;
        }
        // 返回图片插入所需的数据格式
        return {
          url: res.data.downloadUri,
          alt: res.data.filename || file.name,
          href: res.data.downloadUri,
        };
      },
      // 上传失败后触发
      onFailed(file: File, res: any) {
        console.log('upload failed', res);
      },
      // 上传错误后触发
      onError(file: File, err: any, res: any) {
        console.log('upload error', err, res);
      },
    },
  },
};
const defaultToolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'headerSelect',
    // '|',
    // 'header1',
    // 'header2',
    // 'header3',
    // 'header4',
    // 'header5',
    'bold',
    'underline',
    'italic',
    'through',
    // 'code',
    // 'sub',
    // 'sup',
    // 'clearStyle',
    'color',
    'bgColor',
    'fontSize',
    'fontFamily',
    'indent',
    'delIndent',
    'justifyLeft',
    'justifyRight',
    'justifyCenter',
    'justifyJustify',
    'lineHeight',
    'insertImage',
    'uploadImage',
    // 'deleteImage',
    // 'editImage',
    // 'viewImageLink',
    // 'imageWidth30',
    // 'imageWidth50',
    // 'imageWidth100',
    'divider',
    // 'emotion',
    'insertLink',
    'editLink',
    'unLink',
    'viewLink',
    'codeBlock',
    'blockquote',
    'todo',
    'redo',
    'undo',
    'fullScreen',
    // 'enter',
    // 'bulletedList',
    // 'numberedList',
    // 'insertTable',
    // 'deleteTable',
    // 'insertTableRow',
    // 'deleteTableRow',
    // 'insertTableCol',
    // 'deleteTableCol',
    // 'tableHeader',
    // 'tableFullWidth',
    // 'insertVideo',
    // 'uploadVideo',
    // 'editVideoSize',
    // 'uploadImage',
    // 'codeSelectLang',
  ],
};

export default {
  name: 'RichEditor',
};
</script>

<script setup lang="ts">
import { onBeforeUnmount, shallowRef, ref, watch } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { ANY_OBJECT } from '@/types/generic';

import { getZhaokaoInfoById } from '@/api/zhaokao/zhaokao';

const emit = defineEmits<{
  'update:modelValue': [string | undefined];
  getHtml: [string | undefined];
}>();

const props = withDefaults(
  defineProps<{
    modelValue?: string;
    editorConfig?: ANY_OBJECT;
    toolbarConfig?: ANY_OBJECT;
    height?: string;
    isCustomHtml?: boolean;
    content?: string;
    zhaokaoId?: string;
  }>(),
  {
    editorConfig: () => {
      return defaultEditorConfig;
    },
    toolbarConfig: () => {
      return defaultToolbarConfig;
    },
    height: '400px',
    isCustomHtml: false,
  },
);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const mode = ref('default');

const valueHtml = ref(props.modelValue);

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: ANY_OBJECT) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  editor.setHtml(valueHtml.value);
  // console.log('editor', editor);
  // console.log(editor.getAllMenuKeys());
};

watch(
  () => props.modelValue,
  newValue => {
    if (newValue !== valueHtml.value) {

      valueHtml.value = newValue;
    }
  },
  {
    deep: true,
    immediate: true,
  },
);

watch(
  () => valueHtml.value,
  newValue => {
    emit('update:modelValue', newValue);
  },
);
watch(
  () => props.zhaokaoId,
  newValue => {
    if (props.isCustomHtml) {
      setTimeout(() => {
        const editor = editorRef.value;

        if (editor == null) return;

        // 确保编辑器已启用
        if (editor.isDisabled()) editor.enable();

        // 设置焦点
        // if (!editor.isFocused()) editor.focus();

        // 清空选区并删除已选内容
        editor.select([]);
        editor.deleteFragment();
        // 清空
        editor.clear();
        editor.dangerouslyInsertHtml(props.content);

        getZhaokaoInfoById(newValue).then(res => {
          try {
            // editor.dangerouslyInsertHtml(res.data.content);
          } catch (error) {
            console.error('插入HTML内容失败', error);
          }
        });
        // 插入HTML内容
      }, 100);
    }
  },
  {
    immediate: true,
  },
);
const getHtml = () => {
  return editorRef.value ? editorRef.value.getHtml() : undefined;
};

defineExpose({ getHtml });
</script>
